import createAlphabet as ab
from pydub import AudioSegment
from pydub import silence
import paliPlayUtils
import os

# 欢迎语和简单说明
print('''
            这是一个简易巴利语词典,
      查词请在下方输入以“-”短杠分隔音节的单词并回车,退出输入数字“0”，或者按键盘ctrl+“z”按键
      首次运行请忽略fmpeg或avconv编码器缺失错误
    ''')
# 无限循环读取字符串并生成读音

# 创建保存目录
words_path = 'audio/words/'
if not os.path.exists(words_path):
    os.mkdir(words_path)

while (True):
    # 读取字符
    Paliwords = input('请输入单词，并以-分隔音节:')
    if Paliwords == '0':
        break
    # 分割字符串
    betList = Paliwords.split('-')

    # 空字符错误
    if len(betList) == 0 or Paliwords == ' ':
        print('您的输入有误')
        continue
    print('你的单词音节划分结果为：', betList)

    if os.path.exists("audio/words/%s.wav" % Paliwords):
        print('已存在此单词，自动播放音频中······')
        paliPlayUtils.playPaliWord(Paliwords)
        continue
    else:
        print('首次查询，读音正在生成······')
    multiBet = ab.getPaliAlphabet()
    outputMusic = AudioSegment.from_wav("audio/noVoice1s.wav")
    flag = 1
    # errInf = '程序出错'
    for bet in betList:
        if (bet not in ab.allVowels) and (bet not in multiBet) and (bet not in ab.fallingTone):
            print('您的输入有误，%s不是巴利语音节' % bet)
            flag = 0
            break
        else:
            this_path = 'audio/chunks/%s.wav' % bet
            try:
                this_music = AudioSegment.from_wav(this_path)
            except BaseException:
                print('%s 导入错误' % this_path)
                flag = 0
                break
            nsltRange = silence.detect_nonsilent(this_music, min_silence_len=10, silence_thresh=-80)
            if len(nsltRange) == 0:
                pass
            else:
                temp_music = AudioSegment.silent(duration=1)
                for _ in nsltRange:
                    i, j = tuple(_)
                    temp_music += this_music[i:j]
                this_music = temp_music
            outputMusic += this_music
    if flag == 0:
        # print(errInf)
        continue
    else:
        try:
            outputMusic.export("audio/words/%s.wav" % Paliwords, format='wav')
        except BaseException:
            print('%s 导出错误' % Paliwords)
            continue
        print('自动播放音频中······')
        paliPlayUtils.playPaliWord(Paliwords)
        print("文件已保存在audio/words/%s.wav" % Paliwords)
